package storagews.impl;

import storagews.AbstractAuthService;
import core.ws.Storage;
import core.oauth.ServiceFactory;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.QueryParam;
import static org.scribe.model.OAuthConstants.EMPTY_TOKEN;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import javax.ws.rs.core.Response;

/**
 * REST Web Service
 *
 * @author Admin
 */
@Path("auth")
public class AuthService extends ServiceBase implements AbstractAuthService {

    @GET
    @Path("storages")
    @Override
    public Collection<Storage> storages() {
        return session().getStorages();
    }

    @GET
    @Path("tokens")
    @Override
    public int tokens() {
        return session().getTokens().values().size();
    }

    @GET
    @Path("cleartoken")
    @Override
    public Collection<Storage> cleartoken() {
        session().getTokens().clear();
        return storages();
    }

    @GET
    @Path("callback")
    @Override
    public Response callback(
            @QueryParam("code") String code,
            @QueryParam("state") String state) throws URISyntaxException {
        String type = state.substring(0, state.indexOf("_"));
        String callBack = state.substring(type.length() + 1);
        Verifier verifier = new Verifier(code);
        OAuthService service = ServiceFactory.create(type);
        Token token = service.getAccessToken(EMPTY_TOKEN, verifier);
        session().setToken(type, token);
        URI uri = new URI(callBack);
        return Response.seeOther(uri).build();
    }
}
